﻿using Microsoft.AspNetCore.Mvc;

using System.Text.Json;

namespace GitHubCopilotProxies.Handlers;

public class Telemetry
{
    public static async Task GetTelemetryAsync(HttpContext httpContext, [FromServices] IHttpClientFactory httpClientFactory)
    {
        #region 代理转发
        //const string targetUrl = "https://telemetry.individual.githubcopilot.com/telemetry";
        //var requestMessage = new HttpRequestMessage(HttpMethod.Get, targetUrl);
        //requestMessage.Headers.TryAddWithoutValidation("UserAgent", httpContext.Request.Headers.UserAgent.ToString());
        //foreach (var header in httpContext.Request.Headers.Where(kv => kv.Key.StartsWith('x')))
        //    requestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray());
        //using var httpClient = httpClientFactory.CreateClient();
        //var response = await httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead, httpContext.RequestAborted);
        //httpContext.Response.StatusCode = (int)response.StatusCode;
        //foreach (var header in response.Headers)
        //    httpContext.Response.Headers[header.Key] = header.Value.ToArray();
        //using (var responseStream = await response.Content.ReadAsStreamAsync(httpContext.RequestAborted))
        //    await responseStream.CopyToAsync(httpContext.Response.Body, httpContext.RequestAborted);
        #endregion
        // 2025/03/27 示例数据
        const string jsonData = """{"Features":["vsliv368","vspor879","vspor708","vspor363","binariesv615","c4g48928","aa_t_chat_int","cp_jb_t_11731","6074i472","customenabled","cp_compl_c_13691","9064b325","copilot_t_ci","jda6j935","cp_jb_t_3149_ss","4gafe986","31787653","793h1473"],"Flights":{"1j36":"vsliv368","1wr3":"vspor879","1wr7":"vspor708","1wra":"vspor363","2po2":"binariesv615","3w27":"c4g48928","5s3q":"aa_t_chat_int","6fc4":"cp_jb_t_11731","72hu":"6074i472","7494":"customenabled","7533":"cp_compl_c_13691","75eq":"9064b325","75gs":"copilot_t_ci","77g0":"jda6j935","77l4":"cp_jb_t_3149_ss","79wk":"4gafe986","7aeu":"31787653","7aev":"793h1473"},"Configs":[{"Id":"vscode","Parameters":{"aa_t_chat_int":true,"config.chat.experimental.statusIndicator.enabled":true,"config.window.experimentalTitleBarStyle":"custom","copilotchat.config.chat.advanced.inlineEdits.includeCursor":false,"copilotchat.config.chat.advanced.inlineEdits.instructionsVariant":"v1","copilotchat.workspaceChunkSearch.shouldEagerlyInitLocalIndex":true,"copilotpromptcomponents":false,"copilot_ci":true,"idechatenableprojectcontext":true,"idechatprojectcontextfilecountthreshold":10000,"ideenablecopilotedits":true,"livesharecontinuousaa":true,"mindaroBinariesVersion":"1.0.20210615.1","msEntraShowUpdateUserFlow":true,"portForwardingServiceEnabled-development":true,"portForwardingServiceEnabled-production":true,"portForwardingServiceEnabled-staging":true,"shouldUseGrpcService":true,"validate_mi":false}}],"ParameterGroups":null,"FlightingVersion":8324,"ImpressionId":"9A0FCE302938486C8611BB32284ABA0C","AssignmentContext":"vsliv368:30146709;vspor879:30202332;vspor708:30202333;vspor363:30204092;binariesv615:30325510;c4g48928:30535728;aa_t_chat_int:30934572;cp_jb_t_11731:31233879;6074i472:31201624;customenabled:31248079;cp_compl_c_13691:31270498;9064b325:31222308;copilot_t_ci:31222730;jda6j935:31233686;cp_jb_t_3149_ss:31265099;4gafe986:31264396;31787653:31262186;793h1473:31266633;"}""";
        await httpContext.ResponseJsonAsync(jsonData);
    }

    public class TelemetryResponse
    {
        public int ItemsReceived { get; set; }
        public int ItemsAccepted { get; set; }
        public string? AppId { get; set; }
        public List<string> Errors { get; set; } = new List<string>();
    }
    public static async Task<TelemetryResponse> PostTelemetryAsync(HttpContext httpContext, [FromServices] ILogger<Telemetry> logger)
    {
        var response = new TelemetryResponse();
        if (httpContext is not { Request.ContentLength: > 0 }) return response;
        switch (httpContext.Request.ContentType)
        {
            case "application/x-json-stream":
                using (var reader = new StreamReader(httpContext.Request.Body))
                {
                    string? line;
                    while ((line = await reader.ReadLineAsync(httpContext.RequestAborted)) != null)
                    {
                        if (string.IsNullOrWhiteSpace(line)) continue;
                        response.ItemsReceived++;
                        try
                        {
                            //logger.LogInformation("TelemetryString: {line}", line);
                            // 处理遥测数据
                            response.ItemsAccepted++;
                        }
                        catch (Exception ex)
                        {
                            logger.LogError(ex, "解析遥测数据时发生错误");
                            response.Errors.Add(ex.Message);
                        }
                    }
                }
                break;
            case "application/json":
                {
                    try
                    {
                        var jsonDocument = await JsonSerializer.DeserializeAsync<JsonElement>(httpContext.Request.Body, AppJsonSerializerContext.Default.JsonElement, httpContext.RequestAborted);
                        if (jsonDocument is { ValueKind: JsonValueKind.Array })
                            response.ItemsAccepted = response.ItemsReceived = jsonDocument.GetArrayLength();
                        else if (jsonDocument is { ValueKind: JsonValueKind.Object })
                            response.ItemsAccepted = response.ItemsReceived = 1;
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex, "解析遥测数据时发生错误");
                        response.Errors.Add(ex.Message);
                    }
                }
                break;
        }
        return response;
    }

}
